<?php
abstract class Backend_Controller
{
    /**
     * System storage
     * @var Store_Local
     */
    protected $_store;
    /**
     * User object
     * @var User_Admin
     */
    protected $_user;  
    /**
     * Database connection
     * @var Zend_Db_Adapter_Abstract
     */
    protected $_db;  
    /**
     * Module identity, should be defined in child classes
     * @var string
     */
    protected $_module;
    /**
     * Application config
     * @var Config_Abstract
     */
    protected $_configMain;  
    /**
     * Application backend config
     * @var Config_Abstract
     */
    protected $_configBackend;
    /**
     * Resources object
     * @var Resource
     */
    protected $_resource;
    /**
     * Dictionary
     * @var Lang
     */
    protected $_lang;

    
    /**
     * Default controller action
     */   
    abstract public function indexAction();
    
    public function __construct()
    {        
        $this->_store = Application::getStorage();
        $this->_db = Application::getDbConnection();
        $this->_configMain = Application::getConfig();
        $this->_configBackend = $this->_store->get('config_backend');  
        $this->_resource = Resource::getInstance();  
        $this->_lang = Lang::getInstance();

        $this->checkAuth();
    }
    /**
     * Check user permissions and authentication
     */
    public function checkAuth()
    {     
        $name = explode('_', get_called_class());
        $this->_module = $name[1]; 
        
        $userModel = Model_User::getInstance();
        $userModel->checkLogin(true);
         
        $uid = User::isAuthorized();
        if(!$uid || !User::isAdmin())
            $this->loginAction();
            
        $this->_user = User_Admin::getInstance();

        if(!in_array($this->_module, $this->_configBackend->get('system_controllers') ,true) && !$this->_user->canView($this->_module))
            Response::redirect(Request::url(array($this->_configMain->get('adminPath'))));
    }
    
    /**
     * Show login form
     */
    protected function loginAction()
    {        
        $template = new Template();
        Response::put($template->render('./templates/system/'.$this->_configBackend->get('theme').'/login.php'));
        Application::close();
    }
    
    static public function getPostedData($objectName)
    {
    	$lang = Lang::getInstance();
    	
    	$id = Request::post('id','integer',0);
    	
        if($id){
            try {
            	$obj = new Db_Object($objectName, $id);
            }catch (Exception $e){
                Response::jsonError($lang->CANT_EXEC);
            }
        }else{ 
            $obj = new Db_Object($objectName);
            
            if($obj->getConfig()->isRevControl())
            	$obj->set('published' , false);
        }

        $posted = Request::postArray();
        
        $fields= $obj->getFields();
        $errors = array(); 
       
        $uniqGroups = array();
        foreach ($fields as $name)
        {
                if($obj->getConfig()->isRequired($name) && (!isset($posted[$name]) || !strlen($posted[$name]))){
                    $errors[$name] = $lang->CANT_BE_EMPTY;
                    continue;
                }

                if($obj->getConfig()->isBoolean($name) && !isset($posted[$name]))
                	$posted[$name] = false;
                                                  
                if(!array_key_exists($name, $posted))
                    continue;

                try{
                    $obj->set($name,  $posted[$name]);
                }catch (Exception $e){
                    $errors[$name] = $lang->INVALID_VALUE;
                }    
        }   
        
        if(!empty($errors))
             Response::jsonError($lang->FILL_FORM , $errors);
        
        $errors = $obj->validateUniqueValues();

        if(!empty($errors))
          Response::jsonError($lang->FILL_FORM , $errors);
             
        if($id)       
           $obj->setId($id);
    
        return $obj;         
    }
    /**
     * Check edit permissions
     */
    protected function _checkCanEdit(){   	
    	if(!User_Admin::getInstance()->canEdit($this->_module))
            Response::jsonError($this->_lang->CANT_MODIFY);
    }
    /**
     * Check delete permissions
     */
    protected function _checkCanDelete(){
    	if(!User_Admin::getInstance()->canDelete($this->_module))
            Response::jsonError($this->_lang->CANT_DELETE);
    }
}